package com.lxmes.business.service.impl;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import com.lxmes.base.domain.NcSupplier;
import com.lxmes.base.mapper.NcSupplierMapper;
import com.lxmes.business.domain.CcPurchaseInfo;
import com.lxmes.common.utils.DateUtils;
import com.lxmes.common.utils.NewNumber;
import com.lxmes.common.utils.SecurityUtils;
import com.lxmes.sales.domain.NcContract;
import com.lxmes.sales.domain.NcContractDetail;
import com.lxmes.sales.domain.NcContractExamine;
import com.lxmes.sales.mapper.NcContractDetailMapper;
import com.lxmes.sales.mapper.NcContractMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lxmes.common.utils.StringUtils;
import com.lxmes.common.utils.bean.BeanValidators;
import com.lxmes.common.exception.ServiceException;
import javax.validation.Validator;
import com.lxmes.business.mapper.CcPurchaseInfoSpMapper;
import com.lxmes.business.domain.CcPurchaseInfoSp;
import com.lxmes.business.service.ICcPurchaseInfoSpService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 采购审批单Service业务层处理
 * 
 * @author zhangzhiyu
 * @date 2023-06-28
 */
@Service
public class CcPurchaseInfoSpServiceImpl implements ICcPurchaseInfoSpService 
{
    @Autowired
    private CcPurchaseInfoSpMapper ccPurchaseInfoSpMapper;
    @Autowired
    private NcContractMapper contractMapper;

    @Autowired
    protected Validator validator;

    @Autowired
    private  NcSupplierMapper supplierMapper;

    @Autowired
    private NcContractDetailMapper contractDetailMapper;


    /**
     * 查询采购审批单
     * 
     * @param id 采购审批单主键
     * @return 采购审批单
     */
    @Override
    public CcPurchaseInfoSp selectCcPurchaseInfoSpById(Long id)
    {
        return ccPurchaseInfoSpMapper.selectCcPurchaseInfoSpById(id);
    }

    /**
     * 查询采购审批单列表
     * 
     * @param ccPurchaseInfoSp 采购审批单
     * @return 采购审批单
     */
    @Override
    public List<CcPurchaseInfoSp> selectCcPurchaseInfoSpList(CcPurchaseInfoSp ccPurchaseInfoSp)
    {
        ccPurchaseInfoSp.setFactoryCode(SecurityUtils.getFactoryCode());
        return ccPurchaseInfoSpMapper.selectCcPurchaseInfoSpList(ccPurchaseInfoSp);
    }

    @Override
    public List<CcPurchaseInfoSp> selectCcPurchaseInfoSpSelectList(CcPurchaseInfoSp ccPurchaseInfoSp) {
        ccPurchaseInfoSp.setFactoryCode(SecurityUtils.getFactoryCode());
        return ccPurchaseInfoSpMapper.selectCcPurchaseInfoSpSelectList(ccPurchaseInfoSp);
    }

    @Override
    public List<CcPurchaseInfoSp> selectCcPurchaseInfoSpRk(CcPurchaseInfoSp ccPurchaseInfoSp) {
        ccPurchaseInfoSp.setFactoryCode(SecurityUtils.getFactoryCode());
        return ccPurchaseInfoSpMapper.selectCcPurchaseInfoSpRk(ccPurchaseInfoSp);
    }

    /**
     * 新增采购审批单
     * 
     * @param ccPurchaseInfoSp 采购审批单
     * @return 结果
     */
    @Override
    public int insertCcPurchaseInfoSp(CcPurchaseInfoSp ccPurchaseInfoSp)
    {
        ccPurchaseInfoSp.setDeptId(SecurityUtils.getDeptId());
        ccPurchaseInfoSp.setCreateTime(DateUtils.getNowDate());
        return ccPurchaseInfoSpMapper.insertCcPurchaseInfoSp(ccPurchaseInfoSp);
    }

    /**
     * 修改采购审批单
     * 
     * @param ccPurchaseInfoSp 采购审批单
     * @return 结果
     */
    @Override
    public int updateCcPurchaseInfoSp(CcPurchaseInfoSp ccPurchaseInfoSp)
    {
        ccPurchaseInfoSp.setUpdateTime(DateUtils.getNowDate());
        NcSupplier supp = supplierMapper.selectNcSupplierById(ccPurchaseInfoSp.getSupplyId());
        if(supp!=null){
            ccPurchaseInfoSp.setSupplyName(supp.getSupplierName());
        }
        return ccPurchaseInfoSpMapper.updateCcPurchaseInfoSp(ccPurchaseInfoSp);
    }

    @Override
    @Transactional
    public int htsc(Long[] ids) {
        CcPurchaseInfoSp pur1 = ccPurchaseInfoSpMapper.selectCcPurchaseInfoSpById(ids[0]);
        //添加主表
        NcContract ncContract=new NcContract();
        String htNumber= "HT"+NewNumber.createNewNumber(contractMapper.getNewCode(DateUtils.getDate()));
        NcSupplier supp = supplierMapper.selectNcSupplierById(pur1.getSupplyId());
        if(supp==null){
            throw new ServiceException("采购单："+pur1.getDanhao()+"未找到供应商！！！");
        }
        ncContract.setUuid(UUID.randomUUID().toString());
        ncContract.setHbCode(supp.getSupplierCode());
        ncContract.setHbName(supp.getSupplierName());
        ncContract.setHbShuihao(supp.getSupplierEin());
        ncContract.setHbAddress(supp.getAddress());
        ncContract.setHbPhone(supp.getSupplierPhone());
        ncContract.setHbBank(supp.getSupplierBank());
        ncContract.setHbCard(supp.getSupplierAcc());
        ncContract.setContractId(htNumber);
        ncContract.setCreateTime(new Date());
        ncContract.setCreateBy(SecurityUtils.getUsername());
        ncContract.setGcCode(SecurityUtils.getFactoryCode());
        ncContract.setGcName(SecurityUtils.getFactoryName());
        ncContract.setType("2");
        ncContract.setDeptId(SecurityUtils.getDeptId());
        contractMapper.insertNcContract(ncContract);
        for (int i = 0; i <ids.length ; i++) {
            CcPurchaseInfoSp pur = ccPurchaseInfoSpMapper.selectCcPurchaseInfoSpById(ids[i]);
                if(StringUtils.isNull(pur.getSupplyId())){
                    throw new ServiceException("采购单："+pur.getDanhao()+"未找到供应商！！！");
                }
                if(!"1".equals(pur.getShenhState())){
                    throw new ServiceException("采购单："+pur.getDanhao()+"审批未完成");
                }
                if("2".equals(pur.getShenhFlag())){
                    throw new ServiceException("采购单："+pur.getDanhao()+"审批未通过");
                }
                if(StringUtils.isNotEmpty(pur.getContractCode())){
                    throw new ServiceException("采购单："+pur.getDanhao()+"已创建合同");
                }
                NcContractDetail ncContractDetail =new NcContractDetail();
                ncContractDetail.setUuid(UUID.randomUUID().toString());
                ncContractDetail.setMainId(ncContract.getUuid());
                ncContractDetail.setItem(pur.getItemCode());
                ncContractDetail.setItemId(pur.getItemId());
                ncContractDetail.setItemName(pur.getItemName());
                ncContractDetail.setSpec(pur.getSpec());
                ncContractDetail.setContractUnitPrice(pur.getUnitPrice());
                ncContractDetail.setJhUnitPrice(pur.getUnitPrice());
                ncContractDetail.setContractNum(pur.getYhNum());
            contractDetailMapper.insertNcContractDetail(ncContractDetail);
                pur.setContractCode(htNumber);
                pur.setContractNum(pur.getYhNum());
                ccPurchaseInfoSpMapper.updateCcPurchaseInfoSp(pur);
        }

        return 1;
    }

    /**
     * 批量删除采购审批单
     * 
     * @param ids 需要删除的采购审批单主键
     * @return 结果
     */
    @Override
    public int deleteCcPurchaseInfoSpByIds(Long[] ids)
    {
        return ccPurchaseInfoSpMapper.deleteCcPurchaseInfoSpByIds(ids);
    }

    /**
     * 删除采购审批单信息
     * 
     * @param id 采购审批单主键
     * @return 结果
     */
    @Override
    public int deleteCcPurchaseInfoSpById(Long id)
    {
        return ccPurchaseInfoSpMapper.deleteCcPurchaseInfoSpById(id);
    }
    @Override
    public String imporIteminfo(List<CcPurchaseInfoSp> ccPurchaseInfoSpList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(ccPurchaseInfoSpList) || ccPurchaseInfoSpList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (CcPurchaseInfoSp ccPurchaseInfoSp : ccPurchaseInfoSpList)
        {
            try
            {
                BeanValidators.validateWithException(validator, ccPurchaseInfoSp);
                ccPurchaseInfoSp.setCreateBy(operName);
                ccPurchaseInfoSp.setUpdateBy(operName);
                this.insertCcPurchaseInfoSp(ccPurchaseInfoSp);
                successNum++;
                successMsg.append("<br/>" + successNum + "数据导入成功");
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/> 数据导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
